package com.project.handler;

import com.project.dto.Result;
import com.project.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截业务异常，返回业务异常信息
     * @param exception 异常
     * @return Result
     */
    @ExceptionHandler(CustomException.class)
    public Result handleBusinessError(CustomException exception) {
        int code = exception.getCode();
        String message = exception.getMessage();
        return new Result(code, message);
    }

    /**
     * 参数校验错误异常处理
     *
     * @param e 异常
     * @return Result
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result NotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.debug("异常详情 ", e);
        return new Result<>(400, getError(e.getBindingResult().getAllErrors()));
    }

    private String getError(List<ObjectError> allErrors) {
        List<String> message = allErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return message.toString();
    }

    @ExceptionHandler
    public Result errorHandler(Exception e) {
        log.info("异常:{}", e);
        return new Result<>(400,e.getMessage());
    }
}
